using System.Collections.Generic;
using System.Threading.Tasks;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using Marchers.Grpc;
using Microsoft.Extensions.Logging;

namespace Marchers.Grpc
{
    public class AmadeusService : Amadeus.AmadeusBase
    {
        public ILogger<AmadeusService> Logger { get; }

        public AmadeusService(ILogger<AmadeusService> logger)
        {
            this.Logger = logger;

        }

        public override Task<HelloAmadeusResult> HelloAmadeus(Empty request, ServerCallContext context)
        {
            Logger.LogInformation("Call from grpc");
            return Task.FromResult(new HelloAmadeusResult
            {
                Message = "Hello amadeus"
            });
        }

        public override Task<SaveAmadeusResult> SaveAmadeus(SaveAmadeusRequest request, ServerCallContext context)
        {
            Logger.LogInformation("Call save amadeus");
            return Task.FromResult(new SaveAmadeusResult
            {
                Result = $"Save Name: {request.Name}"
            });
        }

        public override async Task TestStream(IAsyncStreamReader<BothTestRequest> requestStream, IServerStreamWriter<BothTestResult> responseStream, ServerCallContext context)
        {
            var bathQueue = new Queue<int>();
            while (await requestStream.MoveNext())
            {
                //将要洗澡的猫加入队列
                bathQueue.Enqueue(requestStream.Current.Id);

                Logger.LogInformation($"testId {requestStream.Current.Id} Enqueue.");
            }

            // 遍历队列开始洗澡
            while (bathQueue.TryDequeue(out var id))
            {
                await responseStream.WriteAsync(new BothTestResult() { Message = $"resuest id: {id}" });

                await Task.Delay(500);//此处主要是为了方便客户端能看出流调用的效果
            }
        }
    }
}